﻿<%@ Application Language="VB" %>
<%@ Import Namespace="System.Security.Principal" %>

<script runat="server">

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application startup
    End Sub
    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application shutdown
    End Sub
        
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when an unhandled error occurs
    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a new session is started
        'Initialize the Cart System
        Session("MyCart") = New CartProducts()
        If Not IsNothing(HttpContext.Current.User.Identity.Name) Then
            Dim authuser As New User(HttpContext.Current.User.Identity.Name)
            Session("UserObject") = authuser
        End If
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a session ends. 
        ' Note: The Session_End event is raised only when the sessionstate mode
        ' is set to InProc in the Web.config file. If session mode is set to StateServer 
        ' or SQLServer, the event is not raised.
    End Sub
    Protected Sub Application_AuthenticateRequest(sender As [Object], e As EventArgs)
        If HttpContext.Current.User IsNot Nothing Then
            If HttpContext.Current.User.Identity.IsAuthenticated Then
                If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
                    Dim id As FormsIdentity = DirectCast(HttpContext.Current.User.Identity, FormsIdentity)
                    Dim ticket As FormsAuthenticationTicket = id.Ticket

                    ' Get the stored user-data, in this case, our roles
                    Dim user As New User(HttpContext.Current.User.Identity.Name)
                    Dim sroles As String = ""
                    If user.isAdmin Then
                        sroles = "Admin"
                    End If
                    Dim roleArray As String() = sroles.Split(","c)
                    HttpContext.Current.User = New GenericPrincipal(id, roleArray)
                End If
            End If
        End If
    End Sub

</script>